#!/bin/bash

script_dir=$(dirname $(realpath $0))
source "${script_dir}/check-toolchain"
source "${script_dir}/config"

rootfs="${tmpdir}/rootfs";
image="${tmpdir}/rootfs.ext4"

echo -e "\033[42m\t\tBuild rootfs\033[0m"
echo "tmpdir: ${tmpdir}"

if [ ! -d $rootfs ]; then
    mkdir $rootfs
fi

if [ -f $image ]; then
    echo "remove old image: $image"
    rm $image
fi  

dd if=/dev/zero of=$image bs=1M count=64
/sbin/mkfs.ext4 $image

sudo mount -t ext4 -o loop $image $rootfs

sudo mkdir "${rootfs}/proc"
sudo mkdir "${rootfs}/lib"
sudo mkdir "${rootfs}/sys"
sudo mkdir "${rootfs}/tmp"
sudo mkdir "${rootfs}/root"
sudo mkdir "${rootfs}/var"
sudo mkdir "${rootfs}/mnt"
sudo mkdir "${rootfs}/dev"

# /etc/init.d/rcS 
sudo mkdir "${rootfs}/etc"
sudo mkdir "${rootfs}/etc/init.d"
sudo cp "${script_dir}/rcS" "${rootfs}/etc/init.d/rcS"
sudo chmod +x "${rootfs}/etc/init.d/rcS"

sudo mknod -m 666 "${rootfs}/dev/tty1" c 4 1
sudo mknod -m 666 "${rootfs}/dev/tty2" c 4 2
sudo mknod -m 666 "${rootfs}/dev/tty3" c 4 3
sudo mknod -m 666 "${rootfs}/dev/tty4" c 4 4

sudo mknod -m 666 "${rootfs}/dev/console" c 5 1
sudo mknod -m 666 "${rootfs}/dev/null" c 1 3

echo "copy libs"
echo  "cp ${gccdir}/lib/*  ${rootfs}/lib"
sudo cp $gccdir/lib/* $rootfs/lib -rap

echo "cp ${busybox}/_install/* $rootfs -ra"
sudo cp $busybox/_install/* $rootfs -rap

sudo umount $rootfs
